/**
 * Created by admin on 2018/1/24.
 */
layui.config({
    base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        $ = layui.jquery;

    $(".show_all").click(function(){
        $.ajax({
            url : "loss/surveryQuery",
            type : "get",
            dataType : "json",
            success : function(data){
            	lossData = data;
                if(window.sessionStorage.getItem("addLoss")){
                    var addLoss = window.sessionStorage.getItem("addLoss");
                    lossData = JSON.parse(addLoss).concat(lossData);
                }
                //执行加载数据的方法
                lossList();
            }
        })
    }) 
    //加载页面数据
    var lossData = '';
    $.ajax({
        url : "loss/surveryQuery",
        type : "get",
        dataType : "json",
        success : function(data){
            lossData = data;
            if(window.sessionStorage.getItem("addLoss")){
                var addLoss = window.sessionStorage.getItem("addLoss");
                lossData = JSON.parse(addLoss).concat(lossData);
            }
            //执行加载数据的方法
            lossList();
        }
    })

    //全文查询
    $(".search_btn").click(function(){
        var newArray = [];
        if($(".search_input").val() != ''){
        	var search_input = $(".search_input").val();
            var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "loss/globalQuery?search_input="+search_input,
                    type : "get",
                    dataType : "json",
                    success : function(data){
                        if(window.sessionStorage.getItem("addLoss")){
                            var addLoss = window.sessionStorage.getItem("addLoss");
                            lossData = JSON.parse(addLoss).concat(data);
                        }else{
                            lossData = data;
                        }
                        for(var i=0;i<lossData.length;i++){
                            var lossStr = lossData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
                            //事故ID
                            if(lossStr.accidentId.indexOf(selectStr) > -1){
                                lossStr["accidentId"] = changeStr(lossStr.accidentId);
                            }
                            //事故名称
                            if(lossStr.accidentName.indexOf(selectStr) > -1){
                                lossStr["accidentName"] = changeStr(lossStr.accidentName);
                            }
                            //损失等级
                            if(lossStr.lossLevel.indexOf(selectStr) > -1){
                                lossStr["lossLevel"] = changeStr(lossStr.lossLevel);
                            }
                            //人员伤亡
                            if(lossStr.number.indexOf(selectStr)>-1){
                                lossStr["number"]=changeStr(lossStr.number);
                            }
                            //经济损失
                            if(lossStr.money.indexOf(selectStr)>-1){
                                lossStr["money"]=changeStr(lossStr.money);
                            }
                            //环境损害
                            if(lossStr.environment.indexOf(selectStr)>-1){
                                lossStr["environment"]=changeStr(lossStr.environment);
                            }
                            if(lossStr.accidentId.indexOf(selectStr)>-1 || lossStr.accidentName.indexOf(selectStr)>-1 || lossStr.lossLevel.indexOf(selectStr)>-1||lossStr.number.indexOf(selectStr)>-1||lossStr.money.indexOf(selectStr)>-1||lossStr.environment.indexOf(selectStr)>-1){
                                newArray.push(lossStr);
                            }
                        }
                        lossData = newArray;
                        lossList(lossData);
                    }
                })

                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })

    //高级查询
    $(".advanced_search").click(function(){
        var newArray = [];
        if($(".accidentId").val() != '' || $(".accidentName").val() != '' || $(".lossLevel").val() != ''
        	|| $(".number").val() != ''|| $(".money").val() != ''|| $(".environment").val() != ''){
        	var params = {};
        	params.accidentId = $(".accidentId").val();
        	params.accidentName = $(".accidentName").val();
        	params.lossLevel = $(".lossLevel").val();
        	params.number = $(".number").val();
        	params.money = $(".money").val();
        	params.environment = $(".environment").val();
        	var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
        	setTimeout(function(){
                $.ajax({
                    url : "loss/advancedQuery",
                    type : "get",
                    data : params,
                    dataType : "json",
                    success : function(data){
                        if(window.sessionStorage.getItem("addLoss")){
                            var addLoss = window.sessionStorage.getItem("addLoss");
                            lossData = JSON.parse(addLoss).concat(data);
                        }else{
                            lossData = data;
                        }
                        for(var i=0;i<lossData.length;i++){
                            var lossStr = lossData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
                            //事故ID
                            if(lossStr.accidentId.indexOf(selectStr) > -1){
                                lossStr["accidentId"] = changeStr(lossStr.accidentId);
                            }
                            //事故名称
                            if(lossStr.accidentName.indexOf(selectStr) > -1){
                                lossStr["accidentName"] = changeStr(lossStr.accidentName);
                            }
                            //损失等级
                            if(lossStr.lossLevel.indexOf(selectStr) > -1){
                                lossStr["lossLevel"] = changeStr(lossStr.lossLevel);
                            }
                            //人员伤亡
                            if(lossStr.number.indexOf(selectStr)>-1){
                                lossStr["number"]=changeStr(lossStr.number);
                            }
                            //经济损失
                            if(lossStr.money.indexOf(selectStr)>-1){
                                lossStr["money"]=changeStr(lossStr.money);
                            }
                            //环境损害
                            if(lossStr.environment.indexOf(selectStr)>-1){
                                lossStr["environment"]=changeStr(lossStr.environment);
                            }
                            if(lossStr.accidentId.indexOf(selectStr)>-1 || lossStr.accidentName.indexOf(selectStr)>-1 || lossStr.lossLevel.indexOf(selectStr)>-1||lossStr.number.indexOf(selectStr)>-1||lossStr.money.indexOf(selectStr)>-1||lossStr.environment.indexOf(selectStr)>-1){
                                newArray.push(lossStr);
                            }
                        }
                        lossData = newArray;
                        lossList(lossData);
                    }
                })

                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })
    //添加损失信息
    $(".lossAdd_btn").click(function(){
        var index = layui.layer.open({
            title : "添加损失信息",
            type : 2,
            content : "lossAdd",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })

    //批量删除
    $(".batchDel").click(function(){
        var $checkbox = $('.loss_list tbody input[type="checkbox"][name="checked"]');
        var $checked = $('.loss_list tbody input[type="checkbox"][name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                setTimeout(function(){
                    //删除数据
                    for(var j=0;j<$checked.length;j++){
                        for(var i=0;i<lossData.length;i++){
                            if(lossData[i].accidentId == $checked.eq(j).parents("tr").find(".loss_del").attr("data-id")){
                            	$.ajax({
                            		url : "loss/delete?accidentId="+lossData[i].accidentId,
                            		type : "post"
                            	})
                                lossData.splice(i,1);
                                lossList(lossData);
                            }
                        }
                    }
                    $('.loss_list thead input[type="checkbox"]').prop("checked",false);
                    form.render();
                    layer.close(index);
                    layer.msg("删除成功");
                },2000);
            })
        }else{
            layer.msg("请选择需要删除的文章");
        }
    })

    //全选
    form.on('checkbox(allChoose)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断信息是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        data.elem.checked;
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })

    //操作


    $("body").on("click",".loss_del",function(){  //删除
        var _this = $(this);
        layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            for(var i=0;i<lossData.length;i++){
                if(lossData[i].accidentId == _this.attr("data-id")){
                	$.ajax({
                		url : "loss/delete?accidentId="+lossData[i].accidentId,
                		type : "post"
                	})
                    lossData.splice(i,1);
                    lossList(lossData);
                }
            }
            layer.close(index);
        });
    })

    function lossList(that){
    	var authorites = [];
        $.ajax({
        	url : "user/authorites",
        	async:false,
        	success : function(data){
        		for(var i=0;i<data.length;i++){
        			authorites.push(data[i].authority);
        		}
        	}
        })
        //渲染数据
        function renderDate(data,curr){
            var dataHtml = '';
            if(!that){
                currData = lossData.concat().splice(curr*nums-nums, nums);
            }else{
                currData = that.concat().splice(curr*nums-nums, nums);
            }
            if(currData.length != 0){
                for(var i=0;i<currData.length;i++){
                	if(authorites.indexOf("ROLE_ADMIN")>-1 || authorites.indexOf("ROLE_INPUT")>-1){
                		dataHtml += '<tr>'
                            +'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                            +'<td>'+currData[i].accidentId+'</td>'
                            +'<td>'+currData[i].accidentName+'</td>'
                            +'<td>'+currData[i].lossLevel+'</td>'
                            +'<td>'+currData[i].number+'</td>'
                            +'<td>'+currData[i].money+'</td>'
                            +'<td>'+currData[i].environment+'</td>'
                            +'<td>'
                            +  '<a class="layui-btn layui-btn-mini layui-btn-normal news_detail loss_info" href="lossSurveryInfo?accidentId='+currData[i].accidentId+'"><i class="layui-icon">&#xe611;</i> 详情</a>'
                            +  '<a class="layui-btn layui-btn-mini loss_edit" href="lossSurveryRevise?accidentId='+currData[i].accidentId+'"><i class="iconfont icon-edit"></i> 编辑</a>'
                            +  '<a class="layui-btn layui-btn-danger layui-btn-mini loss_del" data-id="'+data[i].accidentId+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
                            +'</td>'
                            +'</tr>';
                	}else{
                		dataHtml += '<tr>'
                            +'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                            +'<td>'+currData[i].accidentId+'</td>'
                            +'<td>'+currData[i].accidentName+'</td>'
                            +'<td>'+currData[i].lossLevel+'</td>'
                            +'<td>'+currData[i].number+'</td>'
                            +'<td>'+currData[i].money+'</td>'
                            +'<td>'+currData[i].environment+'</td>'
                            +'<td>'
                            +  '<a class="layui-btn layui-btn-mini layui-btn-normal news_detail loss_info" href="lossSurveryInfo?accidentId='+currData[i].accidentId+'"><i class="layui-icon">&#xe611;</i> 详情</a>'
                            +'</td>'
                            +'</tr>';
                	}
                }
            }else{
                dataHtml = '<tr><td colspan="8" style="text-align: center">暂无数据</td></tr>';
            }
            return dataHtml;
        }

        //分页
        var nums = 5; //每页出现的数据量
        if(that){
            lossData = that;
        }
        laypage({
            cont : "page",
            skip:true,
            pages : Math.ceil(lossData.length/nums),
            jump : function(obj,first){
                $(".loss_content").html(renderDate(lossData,obj.curr));
                $('.loss_list thead input[type="checkbox"]').prop("checked",false);
                form.render();
                if(!first){
                    layer.msg('第'+obj.curr+'页');
                }
            }
        })
    }
})